package com.dbflow5.models;

import com.dbflow5.TestDatabase;
import com.dbflow5.config.FlowManager;
import com.dbflow5.query.SQLite;

import com.dbflow5.BaseUnitTest;
import com.dbflow5.structure.Model;
import org.junit.Assert;
import org.junit.Test;

import java.util.List;

import static org.junit.Assert.*;

public class OneToManyModelTest extends BaseUnitTest {
    @Test
    public void testOneToManyModel() {
        FlowManager.database(TestDatabase.class, db -> {
            SimpleTestModels.TwoColumnModel testModel2 = new SimpleTestModels.TwoColumnModel("Greater", 4);
            Model.save(SimpleTestModels.TwoColumnModel.class, testModel2, db);

            testModel2 = new SimpleTestModels.TwoColumnModel("Lesser", 1);
            Model.save(SimpleTestModels.TwoColumnModel.class, testModel2, db);

            // assert we save
            OneToManyModels.OneToManyModel oneToManyModel = new OneToManyModels.OneToManyModel("HasOrders");
            Model.save(OneToManyModels.OneToManyModel.class, oneToManyModel, db);
            assertTrue(Model.exists(OneToManyModels.OneToManyModel.class, oneToManyModel, db));

            // assert loading works as expected.
            oneToManyModel = SQLite.select().from(OneToManyModels.OneToManyModel.class).requireSingle(db);
            assertNotNull(oneToManyModel.getRelatedOrders(db));
            assertFalse(oneToManyModel.getRelatedOrders(db).isEmpty());

            // assert the deletion cleared the variable
            Model.delete(OneToManyModels.OneToManyModel.class, oneToManyModel, db);
            Assert.assertFalse(Model.exists(OneToManyModels.OneToManyModel.class, oneToManyModel, db));
            assertNull(oneToManyModel.orders);

            // assert singular relationship was deleted.
            List<SimpleTestModels.TwoColumnModel> list = SQLite.select().from(SimpleTestModels.TwoColumnModel.class).queryList(db);
            assertTrue(list != null && list.size() == 1);
            return null;
        });
    }
}
